<template>
  <div class="comment-management">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索评论内容/用户名"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="typeFilter" placeholder="评论类型" clearable @change="handleSearch">
          <el-option label="视频评论" value="video" />
          <el-option label="帖子评论" value="post" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态" clearable @change="handleSearch">
          <el-option label="正常" value="active" />
          <el-option label="已隐藏" value="hidden" />
        </el-select>
      </div>
      <div class="action-bar">
        <el-button type="primary" @click="handleBatchShow" :disabled="!selectedComments.length">
          <el-icon><Check /></el-icon>显示
        </el-button>
        <el-button type="warning" @click="handleBatchHide" :disabled="!selectedComments.length">
          <el-icon><Hide /></el-icon>隐藏
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedComments.length">
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </div>
    </div>

    <!-- 评论列表 -->
    <el-table
      v-loading="loading"
      :data="comments"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column label="评论内容" min-width="400">
        <template #default="{ row }">
          <div class="comment-info">
            <div class="user-info">
              <el-avatar :size="32" :src="row.user?.avatar || '/default-avatar.png'" />
              <span class="username">{{ row.user?.username || '未知用户' }}</span>
            </div>
            <div class="comment-content">
              <div class="text">{{ row.text }}</div>
              <div class="target-info">
                评论于：
                <router-link
                  :to="getTargetLink(row)"
                  class="target-link"
                >
                  {{ getTargetTitle(row) }}
                </router-link>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.targetType === 'video' ? 'success' : 'warning'">
            {{ row.targetType === 'video' ? '视频评论' : '帖子评论' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'warning'">
            {{ row.status === 'active' ? '正常' : '已隐藏' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="点赞数" width="100" align="center">
        <template #default="{ row }">
          <el-tooltip content="点赞数" placement="top">
            <span class="likes-count">
              <el-icon><Star /></el-icon>
              {{ row.likes }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button
              :type="row.status === 'active' ? 'warning' : 'primary'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'active' ? '隐藏' : '显示' }}
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleViewTarget(row)"
            >
              查看来源
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Check, Hide, Delete, Star } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/services/axios.js' // 确认导入的是配置好的实例
import { formatDate } from '@/utils/formatters.js'

const router = useRouter()

// 查询参数
const searchQuery = ref('')
const typeFilter = ref('')
const statusFilter = ref('')

// 表格数据
const comments = ref([])
const loading = ref(false)
const selectedComments = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取评论列表
const fetchComments = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      search: searchQuery.value,
      type: typeFilter.value,
      status: statusFilter.value
    }
    // 修改 API 路径为管理员接口
    const response = await http.get('/api/admin/comments', { params })
    comments.value = response.data.comments
    total.value = response.data.totalComments // 修正 total 字段
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 切换评论状态
const handleToggleStatus = async (comment) => {
  try {
    const newStatus = comment.status === 'active' ? 'hidden' : 'active'
    await http.patch(`/api/admin/comments/${comment._id}/status`, { status: newStatus })
    comment.status = newStatus
    ElMessage.success(`评论已${newStatus === 'active' ? '显示' : '隐藏'}`)
  } catch (error) {
    console.error('更新评论状态失败:', error)
    ElMessage.error('更新评论状态失败')
  }
}

// 删除评论
const handleDelete = async (comment) => {
  try {
    await ElMessageBox.confirm('确定要删除此评论吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await http.delete(`/api/admin/comments/${comment._id}`)
    ElMessage.success('删除成功')
    // 从列表中移除
    const index = comments.value.findIndex(c => c._id === comment._id)
    if (index !== -1) {
      comments.value.splice(index, 1)
      total.value -= 1
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  }
}

// 批量操作
const handleBatchAction = async (action) => {
  if (!selectedComments.value.length) return
  
  const actionMap = {
    show: { text: '显示', status: 'active' },
    hide: { text: '隐藏', status: 'hidden' },
    delete: { text: '删除', api: 'delete' }
  }
  
  const actionInfo = actionMap[action]
  if (!actionInfo) return
  
  try {
    await ElMessageBox.confirm(
      `确定要${actionInfo.text}选中的 ${selectedComments.value.length} 条评论吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (action === 'delete') {
      const commentIds = selectedComments.value.map(comment => comment._id)
      await http.delete('/api/admin/comments', { data: { ids: commentIds } })
      ElMessage.success('批量删除成功')
      fetchComments()
    } else {
      // 批量更新状态
      const commentIds = selectedComments.value.map(comment => comment._id)
      await http.patch('/api/admin/comments/status', { 
        ids: commentIds, 
        status: actionInfo.status 
      })
      ElMessage.success(`批量${actionInfo.text}成功`)
      fetchComments()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`批量${actionInfo.text}失败:`, error)
      ElMessage.error(`批量${actionInfo.text}失败`)
    }
  }
}

// 获取目标链接
const getTargetLink = (comment) => {
  if (comment.targetType === 'video') {
    return `/video/${comment.targetId}`
  } else {
    return `/post/${comment.targetId}`
  }
}

// 获取目标标题
const getTargetTitle = (comment) => {
  return comment.targetTitle || '已删除的内容'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchComments()
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedComments.value = selection
}

const handleBatchShow = () => handleBatchAction('show')
const handleBatchHide = () => handleBatchAction('hide')
const handleBatchDelete = () => handleBatchAction('delete')

// 查看评论来源
const handleViewTarget = (comment) => {
  router.push(getTargetLink(comment))
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchComments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchComments()
}

// 初始化
onMounted(() => {
  fetchComments()
})
</script>

<style scoped>
.comment-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
}

.search-bar .el-input {
  width: 200px;
}

.comment-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: bold;
}

.comment-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.text {
  color: #303133;
  line-height: 1.5;
}

.target-info {
  font-size: 13px;
  color: #909399;
}

.target-link {
  color: #409eff;
  text-decoration: none;
}

.target-link:hover {
  text-decoration: underline;
}

.likes-count {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>